package com.sfdk.io
{
import com.sfdk.events.ResourcesEvent;
import com.sfdk.io.data.URLObject;
import com.sfdk.log.Logger;
import com.sfdk.resources.ResourcesLoader;

import flash.display.Loader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;

public class SWFLoader extends EventDispatcher
	{
		private var _urls : Vector.<URLObject>;
		private var _currentIndex : int;
		private var _loader : Loader;
		private var _loaderContext : LoaderContext;
		private var _toDispatch : String;
		private var _parent : ResourcesLoader;
		private const resourcesPath : String = "http://www.lushu.org/";
		
		/**
		 * Chargement des ressources de type SWF.
		 * 
		 * @param urls un Array avec les valeurs des urls
		 * @param newVersion Boolean pour vérifier si on doit utiliser le cache ou non
		 * @param local Boolean pour vérifier si on travaille en local
		 **/
		public function SWFLoader(urls : Vector.<URLObject>, resourceLoader : ResourcesLoader) : void
		{
			if(urls == null || urls.length == 0)
				Logger.error("There are no resources to load");
			_urls = urls;
			
			_parent = resourceLoader;	
			
			_currentIndex = 0;

			_loader = new Loader();
			_loaderContext = new LoaderContext(false,ApplicationDomain.currentDomain);
			// On ajoute un listener qui vérifie si le loading est fini
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, next, false, 0, true);
			
			doLoad();
		}
		
		private function doLoad() : void
		{
			var urlObj : URLObject =  _urls[_currentIndex];
			
			var toLoad : String = urlObj.url;
			_toDispatch = urlObj.event;
				 				
//			var rFactor:int=Math.floor(Math.random()*10000);
//			toLoad.concat(rFactor.toString());

			var urlRequest : URLRequest = new URLRequest(toLoad);
			var requestHeader:URLRequestHeader = new URLRequestHeader("Cache-Control","no-cache");
			urlRequest.requestHeaders = [requestHeader];
			_loader.load(urlRequest,_loaderContext);	
		}

		private function next(event : Event) : void
		{
			dispatchEvent(new ResourcesEvent(ResourcesEvent.RESOURCE_LOADED));
			if (_toDispatch != "")
			{
				_parent.dispatchEvent(new ResourcesEvent(_toDispatch));
				_toDispatch = "";
			}
			_currentIndex++;
			if (_currentIndex >= _urls.length)
			{
				// On a tout loader
				_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, next);
				dispatchEvent(new ResourcesEvent(ResourcesEvent.RESOURCES_LOADED));
			}
			else
				doLoad();
		}
		
		public function dispose() : void
		{
			_urls = null;
			_loader = null;
			_parent = null;
			_loaderContext = null;
			_toDispatch = null;
		}
	}
}